package com.hddz.acquisition.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.jb.Preference;
import android.jb.barcode.BarcodeManager;
import android.jb.utils.WakeLockUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hddz.acquisition.AcquistionApp;
import com.hddz.acquisition.AppSetting;
import com.hddz.acquisition.DialogJst;
import com.hddz.acquisition.GlobalConst;
import com.hddz.acquisition.R;
import com.hddz.acquisition.SmartCallBack;
import com.hddz.acquisition.SoundUtil;
import com.hddz.acquisition.XUtil;
import com.hddz.acquisition.barcode.ScanListener;
import com.hddz.acquisition.barcode.ScanService;
import com.hddz.acquisition.model.Command;
import com.hddz.acquisition.model.JsonRespose;
import com.hddz.acquisition.view.DialogHelper;

import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressLint("Registered")
public abstract class BaseActivity extends FragmentActivity implements ScanListener, IScanAction {

    private static final String TAG = "BaseActivity";
    public String GUID = java.util.UUID.randomUUID().toString();
    @SuppressLint("SimpleDateFormat")
    public SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    WakeLockUtil mWakeLockUtil = null;
    private Intent service;
    private ScanService scanService;
    private BarcodeManager scanManager;
    boolean bind = false;
    private boolean isScanShortcutSupport = false;
    public long nowTime = 0;
    public long lastTime = 0;
    private long clicknowTime = 0;
    private long clicklastTime = 0;
    private String codeType;
    private String context;

    public SoundUtil soundUtil;
    private byte[] codeBuffer;


    public DialogHelper dialogHelper;

    private boolean isScan = false;
    public String targetwarehouse = "";
    public String currentCmd = "";

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1000:
                    mWakeLockUtil.lock();// 保持屏幕唤醒
                    break;
                case 1001:
                    mWakeLockUtil.unLock();// 屏幕不保持唤醒
                    break;
                case GlobalConst.Handler_SHOW_RESULT:
                    if (null != codeBuffer) {
                        byte[] tempb = new byte[codeBuffer.length];
                        int j = 0;
                        for (int i = 0; i < codeBuffer.length; i++) {
                            if (codeBuffer[i] >= 0x30 && codeBuffer[i] <= 0x39) {
                                tempb[j] = codeBuffer[i];
                                j++;
                            }
                        }
                        byte[] tempc = new byte[j];
                        System.arraycopy(tempb, 0, tempc, 0, j);
                        codeBuffer = tempc;
                        String str = new String(codeBuffer);
                        soundUtil.playBeep();

                        receiveCode(str);
                        Log.e("ddd", str);
                    }
                    break;
                case 8:
                    Log.e("ddd", context);
                    receiveCode(context);
                    break;
                case GlobalConst.Handler_ADD_RESPONSE:
                    JsonRespose json = (JsonRespose) msg.obj;
                    addResponse(json);
                    break;
                case GlobalConst.Handler_ADD_ERROR:
                    addErr((String) msg.obj);
                    break;
                case 777:// 刷新UI
//                    if(null != scanManager){
//                        tv_all_count.setText(""+scanManager.getScan_count());
//                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bind = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bind = true;
            ScanService.MyBinder myBinder = (ScanService.MyBinder) service;
            scanService = myBinder.getService();
            //
            scanManager = scanService.getScanManager();

            scanService.setOnScanListener(BaseActivity.this);
            scanService.setActivityUp(true);

            if (AppSetting.getAppSetting(BaseActivity.this).IS_FIRST.get()) {
                if (scanManager.getScannerModel() != 4) {
                    scanManager.setScannerModel(4);
                    sendBroadcast(new Intent("ReLoadCom"));
                }
                Preference.setScanShortcutSupport(BaseActivity.this, true);
                if(null != scanService){
                    scanService.setIsScanShortcutSupport(true);
                }
                AppSetting.getAppSetting(BaseActivity.this).IS_FIRST.set(false);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        x.view().inject(this);

        dialogHelper = new DialogHelper(this);
        soundUtil = new SoundUtil(this, true, false);


        /**
         * 监听橙色按钮按键广播
         */
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("com.jb.action.F4key");
//        registerReceiver(f4Receiver, intentFilter);


        //启动监听
        service = new Intent(this, ScanService.class);
        startService(service);
        bindService(service, serviceConnection, BIND_AUTO_CREATE);
        mWakeLockUtil = new WakeLockUtil(this);

        Preference.setScanSelfopenSupport(this, true);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (scanService != null)
            scanService.setActivityUp(false);
        ScanService.isScanActivityUp = true;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        if (scanService != null)
            scanService.setActivityUp(true);
        ScanService.isScanActivityUp = false;
        isScanShortcutSupport = Preference.getScanShortcutSupport(this, true);

    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if (null != scanManager) {
            scanManager.Barcode_Close();
            scanManager.Barcode_Stop();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        if (scanService != null) {
            if (null != scanManager) {
                System.out.println("ScanActivity Barcode_Stop5");
                scanManager.Barcode_Stop();
            }
        }

        if (bind) {
            unbindService(serviceConnection);
            if (!Preference.getScanSelfopenSupport(this, true)) {
                this.stopService(service);
            }
        }

        mWakeLockUtil.unLock();//

//        if (null != f4Receiver) {
//            this.unregisterReceiver(f4Receiver);
//        }

    }

    @Override
    public void result(String content) {
        mHandler.sendMessage(mHandler.obtainMessage(5, content));
    }

    @Override
    public void henResult(String codeType, String context) {
        Log.d(TAG, "henResult receiv:" + context);
        this.codeType = codeType;
        this.context = context;
        mHandler.sendEmptyMessage(8);
    }


    /**
     * 捕获扫描物理按键广播
     */
    private BroadcastReceiver f4Receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // Bundle bundle = intent.getExtras();
            if (intent.hasExtra("F4key")) {
                if (intent.getStringExtra("F4key").equals("down")) {
                    if (isScanShortcutSupport) {
                        clicknowTime = System.currentTimeMillis();
                        if (clicknowTime - clicklastTime > 200) {
                            Log.e("ScanActivity:", "F4key down");
                            clicklastTime = clicknowTime;
                            mHandler.sendEmptyMessageDelayed(777, 100);
                        }
                    }

                } else if (intent.getStringExtra("F4key").equals("up")) {

                }
            }
        }
    };


    @Event(R.id.btn_back)
    private void onBack(View view) {
        finish();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_UP) {
            Log.d("Key", "Enter Key:" + event.getKeyCode());
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_BACK:
                    backDo();
                    return true;
                case KeyEvent.KEYCODE_ENTER:
                    if (!isScan) {
                        finishDo();
                    }
                    return true;
                case KeyEvent.KEYCODE_F2:
                    nowTime = System.currentTimeMillis();
                    scanManager.Barcode_Stop();
                    // 按键时间不低于200ms
                    if (nowTime - lastTime > 200) {
                        System.out.println("scan(0)");
                        if (null != scanManager) {
                            scanManager.Barcode_Start();
                        }
                        lastTime = nowTime;
                    }
                    return true;
                default:
                    break;
            }
            if (event.getKeyCode() == KeyEvent.KEYCODE_F9) {
                isScan = true;
            } else {
                isScan = false;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    public void baseSendCommandWithTargetwarehouse(String cmd, String targetwarehouse) {
        baseSendCommand(cmd, "", "", targetwarehouse, "", "", "", GUID, smartCallBack);
    }

    public void baseSendCommandWithFree(String cmd, String invcode, String free) {
        baseSendCommand(cmd, "", "", targetwarehouse, "", free, invcode, GUID, smartCallBack);
    }

    public void baseSendCommand(String cmd, String barcode, String sourcewarehouse, String targetwarehouse) {
        baseSendCommand(cmd, barcode, sourcewarehouse, targetwarehouse, "", "", "", GUID, smartCallBack);
    }

    public void baseSendCommand(String cmd, String barcode) {
        baseSendCommand(cmd, barcode, "", targetwarehouse, "", "", "", GUID, smartCallBack);
    }

    public void baseSendCommand(String cmd, String barcode, String price) {
        baseSendCommand(cmd, barcode, "", targetwarehouse, price, "", "", GUID, smartCallBack);
    }

    public void baseSendCommand(String cmd, String barcode,String sourcewarehouse, String targetwarehouse,String price) {
        baseSendCommand(cmd, barcode, sourcewarehouse, targetwarehouse, price, "", "", GUID, smartCallBack);
    }


    public void baseSendCommand(final String cmd, String barcode, String sourcewarehouse,
                                String targetwarehouse, String price, String free, String invcode, String guid, SmartCallBack callBack) {
        callBack.cmd = cmd;
        if (DialogJst.isLoading()) {
            return;
        }
        String url = "http://"
                + AppSetting.getAppSetting(AcquistionApp.getInstance()).SERVER_ADDRESS
                .get() + "/HoldHandler.ashx";
        Command command = new Command();
        command.command = cmd;
        command.guid = guid;
        command.datetime = format.format(new Date());
        command.barcode = barcode;
        command.holdname = AppSetting.getAppSetting(getApplicationContext()).UN
                .get();
        command.sourcewarehouse = sourcewarehouse;
        if (price != null && price.length() > 0)
            command.price = price;
        command.targetwarehouse = targetwarehouse;
        command.importtype = AppSetting.getAppSetting(getApplicationContext()).IMPORT_TYPE
                .get();
        command.vouchtype = AppSetting.getAppSetting(getApplicationContext()).VOUCH_TYPE
                .get();
        command.invcode = invcode;
        command.free1 = free;

        DialogJst.startLoading(BaseActivity.this);
        XUtil.PostJson(url, command, callBack);
    }


    private SmartCallBack<JsonRespose> smartCallBack = new SmartCallBack<JsonRespose>() {


        @Override
        public void onCancelled(CancelledException cex) {
            super.onCancelled(cex);
            DialogJst.stopLoading();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            super.onError(ex, isOnCallback);
            DialogJst.stopLoading();
            soundUtil.playAir();
            Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onFinished() {
            super.onFinished();
            DialogJst.stopLoading();
        }

        @Override
        public void onSuccess(JsonRespose result) {
            super.onSuccess(result);
            DialogJst.stopLoading();
            Message msg = new Message();
            if (result.code > 0) {
                currentCmd = cmd;
                msg.obj = result;
                msg.what = GlobalConst.Handler_ADD_RESPONSE;
                soundUtil.playEnd();
            } else {
                msg.obj = result.message;
                msg.what = GlobalConst.Handler_ADD_ERROR;
                soundUtil.playTip();
            }
            mHandler.sendMessage(msg);
        }
    };

    public void successMethod() {

    }

}
